package com.cmxh.shipper.controller;

import com.cmxh.shipper.pojo.DriverUser;
import com.cmxh.shipper.service.DriverUserService;
import com.cmxh.shipper.util.*;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/*
 * 用户表Controller
 */
@RestController
public class DriverUsercontroller {
    @Autowired
    private DriverUserService driverUserService;
    @Autowired
    private SevdMessage sevdMessage;

    @Autowired
    private RedisTemplate<String, Object> xx;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    //修改新增密码
    @RequestMapping("/user/updatepassword")
    public Result updatePassword(@RequestBody DriverUser driverUser) {
        System.out.println("driverUser = " + driverUser);
        String inputEncrypt = Md5Util.encrypt(driverUser.getPassword());
        driverUser.setPassword(inputEncrypt);
        System.out.println("driverUser = " + driverUser);
        if (driverUser.getPassword()==null || driverUser.getPassword()==""){
            if (!driverUser.getOldpassword().equals(driverUser.getPassword())){
                return new Result(Code.GET_ERR,"旧密码错误");
            }
        }
        int updatePassword = driverUserService.updatePassword(driverUser);
        if (updatePassword > 0) {
            return new Result(Code.SAVE_OK, "修改成功");
        }else {
            return new Result(Code.SAVE_ERR, "修改失败");
        }
    }


    // 添加用户
    @RequestMapping("/addyonghu")
    public Result addyonghu(@RequestBody DriverUser driverUser) {
        int insert = driverUserService.insert(driverUser);
        if (insert > 0) {
            return new Result(Code.SAVE_OK, "添加成功");
        } else {
            return new Result(Code.SAVE_ERR, "添加失败");
        }
    }

    // 账号密码登录
    @RequestMapping("/queryyonghu")
    public Result queryyonghu(@RequestBody DriverUser driverUser) {
        DriverUser logins = driverUserService.logins(driverUser);
        if (logins == null) {
            return new Result(Code.GET_ERR, "用户名不存在");
        } else {
            // 对用户输入的密码进行加密
            String inputEncrypt = Md5Util.encrypt(driverUser.getPassword());
            if (inputEncrypt.equals(logins.getPassword())) {
                // 用户名也对 密码也对
                // 我们需要把这个人拥有的权限和角色查询回来 放到redis当中  为了后续spring security认证和鉴权做准备
                LoginUser loginUser = new LoginUser();
                loginUser.setName(logins.getPhone());
                loginUser.setPwd(inputEncrypt); // 加密的密码

                xx.opsForValue().set(logins.getPhone(),loginUser);
                // 然后再下发牌牌
                // 生成一个JWT的字符串
                Map maps = new HashMap<>();
                maps.put("username",logins.getPhone());
                String jwt = jwtTokenUtil.generateToken(maps);

                Map<String, Object> map = new HashMap<>();
                map.put("jwt", jwt);
                map.put("duixiang", logins);
                return new Result(Code.GET_OK, map, "查询成功");
            } else {
                return new Result(Code.GET_ERR, "密码错误");
            }
        }
    }

    // 验证码登录
    @RequestMapping("/yanzheng/{phone}")
    public Result code(@PathVariable String phone) {
        int code = (int) (Math.random() * 899999) + 100000;
        sevdMessage.sendcode(phone, code + ""); // 假设sendcode方法会发送验证码到用户手机

        // 存储验证码到Redis，1分钟过期
        xx.opsForValue().set("code:" + phone, code, 1, TimeUnit.MINUTES);

        // 查询用户信息
        DriverUser driverUser = driverUserService.selectByPrimaryKey(phone);

        // 如果用户存在，存储用户信息到Redis
        if (driverUser != null) {
            xx.opsForValue().set("user:" + phone, driverUser, 30, TimeUnit.MINUTES);
        }

        return new Result(Code.GET_OK, code, "验证码发送成功");
    }

    // 验证码注册/登录
    @RequestMapping("/zhuce/{phone}/{code}")
    public Result zhuce(@PathVariable String phone, @PathVariable String code) {
        // 1. 根据手机号去redis中取验证码
        String redisCodeKey = "code:" + phone;
        Object o = xx.opsForValue().get(redisCodeKey);
        if (o == null) {
            return new Result(Code.GET_ERR, "验证码过期");
        } else {
            if (code.equals(o.toString())) {
                // 验证码正确，创建新的JWT Token
                // 从Redis获取用户信息
                String redisUserKey = "user:" + phone;
                DriverUser driverUser = driverUserService.selectByPrimaryKey(phone);
                if (driverUser == null) {
                    // 用户不存在，创建新用户
                    DriverUser DD = new DriverUser();
                    DD.setPhone(phone);
                    DD.setTypeid(2);
                    int insert = driverUserService.insertPhone(DD);

                    if (insert > 0) {
                        LoginUser loginUser = new LoginUser();
                        loginUser.setName(phone);

                        xx.opsForValue().set(phone,loginUser);
                        Map maps = new HashMap<>();
                        maps.put("username",phone);
                        String jwtToken = jwtTokenUtil.generateToken(maps);
                        // 将用户信息存入Redis，30分钟过期
                        Map<String, Object> response = new HashMap<>();
                        response.put("jwt", jwtToken);
                        response.put("user", DD);
                        response.put("message", "注册成功");
                        return new Result(Code.GET_OK, response, "注册成功");
                    } else {
                        return new Result(Code.GET_ERR, "注册失败");
                    }
                } else {

                    LoginUser loginUser = new LoginUser();
                    loginUser.setName(phone);

                    xx.opsForValue().set(phone,loginUser);
                    Map maps = new HashMap<>();
                    maps.put("username",phone);
                    String jwtToken = jwtTokenUtil.generateToken(maps);
                    // 用户已存在，直接生成Token
                    Map<String, Object> response = new HashMap<>();
                    response.put("jwt", jwtToken);
                    response.put("message", "登录成功");
                    response.put("user", driverUser);
                    return new Result(Code.GET_OK, response, "登录成功");
                }
            } else {
                return new Result(Code.GET_ERR, "验证码错误");
            }
        }
    }
}
